<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\dic\DicOutput;
use app\dic\DicProduct;
use think\App;
use util\Excel;
use util\Token;

use think\exception\ValidateException;
use think\facade\Log;

/**
 * 采购管理控制器
 */
class Output extends AdminBase
{

    protected $model = null;
    protected $adminId = null;
    protected $token = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Product();

        $this->validate = \app\admin\validate\Output::class;
        $this->token = $this->request->header('token');
        $adminId = Token::userId($this->token);
        $this->adminId = $adminId;
    }

    //商品库存列表
    public function index()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);

        $where['site_id'] = 37;
        $where['status'] = DicProduct::$product_status_active;
        // halt($where);
        $list = $this->model
            ->where($where)
            ->field('id,images,brand,purchase_cost,arrive_day')
            ->order($sortArr)
            ->paginate($limit);
        $lists = $list->items();
        // $images = table('product_info')->select()->toarray();
        // $images = array_column($images, 'pic1image', 'brand');
        foreach ($lists as $k => $v) {
            //查询商品id里面的title
            $title = table('brand')->where(['product_id' => $v['id']])->find();
            $title = !empty($title['title']) ? $title['title'] : '';
            // $brand = strtolower($title);
            // halt($images, $brand);
            //通过标题查询采购成本
            $brand_cost = table('procurement_cost')->where(['number' => $title])->order(['timedate' => 'desc'])->find();
            $list[$k]['purchase_cost'] =  !empty($brand_cost['material']) ? $brand_cost['material'] : 0;
            // $lists[$k]['images'] = isset($images[$brand]) ? $images[$brand] : '';
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $list->items(),
        ];

        return json($data);
    }

    //更新到货天数

    public function update_arrive_day()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {

                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        return success('ok', $row);
    }



    //添加采购申请
    public function add_purchase_apply()
    {

        $post = $this->request->post();
        // halt($post);
        //bra54 8030828921051    bra01   7969504854235
        $product_id = !empty($post['product_id']) ? $post['product_id'] : 8030828921051;
        //补货数量
        $rep_num = !empty($post['rep_num']) ? $post['rep_num'] : 0;
        $order_num = !empty($post['order_num']) ? $post['order_num'] : 0;
        $product_variants = table('productvariants')->where(['product_id' => $product_id])->select()->toarray();
        $color = array_values(array_unique(array_column($product_variants, 'option1')));
        $size = array_values(array_unique(array_column($product_variants, 'option2')));
        $cup = array_values(array_unique(array_column($product_variants, 'option3')));
        if (!empty($size) && !empty($cup)) {
            foreach ($size as  $v) {
                foreach ($cup as  $vl) {
                    $size_cup[] = $v . $vl;
                }
            }
        } else {
            $size_cup = $size;
        }
        array_unshift($size_cup, 'color');
        array_push($size_cup, 'color_sum');
        $table_header = $size_cup;
        if (count($post) == 1) {
            //为1显示列表数据
            $table_header_list = $table_header;
            foreach ($table_header_list as $key => $value) {
                $table_header_list[$key] = '';
            }
            foreach ($color as $key) {
                $list[] = array_values($table_header_list);
            }
            $data = [
                'code' => 1,
                'msg' => '',
                'table_header' => $table_header,
                'product_id' => $product_id,
                'data' => $list,
                'options' => get_options($color),
            ];
            return json($data);
        }
        // $data = $post['sku'];
        $product_id = $post['product_id'];
        $purchase_data = $post['data'];
        $apply_type = $post['apply_type'];
        $brand  = table('brand')->where(['product_id' => $product_id])->find();
        // halt($data);
        $batch = date('Ymd') . rand(1000, 9999);
        $time = date('Y-m-d H:i:s', time());
        foreach ($purchase_data as $key => $purchase) {
            $color = $purchase['color'];
            unset($purchase['color'], $purchase['统计']);
            foreach ($purchase as $purchase_key => $purchase_value) {
                if (!empty($purchase_value)) {
                    table('purchase')->insert([
                        'sku' => $purchase_key,
                        'color' => $color,
                        'num' => $purchase_value,
                        'admin_id' => $this->adminId,
                        //1待审 2 已审核
                        'product_id' => $product_id,
                        'apply_type' => $apply_type,
                        'batch' => $batch,
                        'brand' => !empty($brand['title']) ? $brand['title'] : '',
                        'apply_time' => $time,
                    ]);
                }
            }
        }
        return success('申请成功');

        // $brand = table('brand')->where(['product_id' => $product_id])->find();
        // $insert_detail_data = [
        //     'batch' => $batch,
        //     'admin_id' => $this->adminId,
        //     'brand' => isset($brand['title']) ? $brand['title'] : '',
        //     'rep_num' => $rep_num,
        //     'apply_time' => $time,
        //     'product_id' => $product_id,
        // ];
        // table('check')->insert($insert_detail_data);
    }


    //采购申请列表
    public function add_purchase_apply_list()
    {
        $post = $this->request->post();
        //获取id值
        $product_id = !empty($post['product_id']) ? $post['product_id'] : '8049602265307';
        $where = [];
        $product_variants = table('productvariants')->where(['product_id' => $product_id])->select()->toarray();
        $color = array_values(array_unique(array_column($product_variants, 'option1')));
        $size = array_values(array_unique(array_column($product_variants, 'option2')));
        $cup = array_values(array_unique(array_column($product_variants, 'option3')));
        if (!empty($size) && !empty($cup)) {
            foreach ($size as  $v) {
                foreach ($cup as  $vl) {
                    $size_cup[] = $v . $vl;
                }
            }
        } else {
            $size_cup = $size;
        }
        array_unshift($size_cup, 'color');
        array_push($size_cup, 'color_sum');
        array_push($size_cup, 'create_time');
        $table_header = $size_cup;
        $table_header =  get_table_header($table_header);
        $is_superadmin = Token::is_superadmin($this->token);
        if (!$is_superadmin) {
            $where[] = ['admin_id', '=', $this->adminId];
        }
        $where[] = ['product_id', '=', $product_id];
        $list = mgtable('purchase')->order('create_time', 'desc')->where($where)->select()->toarray();
        $count = mgtable('purchase')->where($where)->count();
        if (!$list) {
            return [];
        }
        foreach ($list as $key => $value) {
            $admin = table('system_admin')->where(['id' => $value['admin_id']])->find();
            $list[$key]['create_time'] =  date('Y-m-d H:i:s', $value['create_time']);
            $list[$key]['admin_id'] = isset($admin['nickname']) ? $admin['nickname'] : '';
            $list[$key]['status'] = DicOutput::get_status($value['status']);
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $count,
            'data' => $list,
            'table_header' => $table_header,
        ];
        return json($data);
    }
    //更新采购成本
    public function update_purchase_cost()
    {
        $post = $this->request->post();
        $product_id = !empty($post['product_id']) ? $post['product_id'] : 6643240140873;
        $purchase_cost = !empty($post['purchase_cost']) ? $post['purchase_cost'] : 0;
        table('product')->where(['id' => $product_id])->update(['purchase_cost' => $purchase_cost]);
        return success('修改成功');
    }

    //待采购数据数据操作
    public function edit_purchase_apply()
    {
        $post = $this->request->post();
        //是否保存草稿
        if (isset($post['is_draft']) && $post['is_draft']) {
            $is_draft = 1;
        } else {
            $is_draft = 0;
        }
        $id = !empty($post['id']) ? $post['id'] : 0;
        //采购信息
        $purchase_info  = table('purchase')->where(['id' => $id])->find();
        //合并之后的批次号
        $union_batch = !empty($purchase_info['union_batch']) ? $purchase_info['union_batch'] : '';
        $dcg_info = table('dcg')->where(['union_batch' => $union_batch])->find();
        $purchase_data = table('purchase')->field('id,sku,color,num,real_num')->where(['union_batch' => $union_batch])->select()->toarray();
        if (empty($dcg_info)) {
            //插入
            $data = [
                'order_num' => $post['order_num'],
                'union_batch' => $union_batch,
                'purchase_price' => $post['purchase_price'],
                'wl_num' => $post['wl_num'],
                'real_num' => $post['real_num'],
                'sum_num' => $post['sum_num'],
                'addtime' => date('Y-m-d H:i:s'),
            ];
            table('dcg')->where(['union_batch' => $post['union_batch']])->insert($data);
            //更新对应的数量
            foreach ($purchase_data as $key => $value) {
                table('purchase')->where(['id' => $value['id']])->update(['real_num' => $value['real_num']]);
            }
            $dcg_info = table('dcg')->where(['union_batch' => $union_batch])->find();
        }
        if (!empty($dcg_info) && count($post) > 1) {
            //回显数据
            if ($post['display'] == 1) {
                $msg = '回显数据';
                //物流单号
                if (!empty($dcg_info['wl_num'])) {
                    $dcg_info['wl_num'] = explode(',', $dcg_info['wl_num']);
                } else {
                    $dcg_info['wl_num'] = [];
                }
                //1688单号
                if (!empty($dcg_info['order_num'])) {
                    $dcg_info['order_num'] = explode(',', $dcg_info['order_num']);
                } else {
                    $dcg_info['order_num'] = [];
                }
                foreach ($purchase_data as $k => $v) {
                    $purchase_data[$k]['sku'] = $v['color'] . '-' . $v['sku'];
                    $purchase_data[$k]['editname'] = false;
                    $purchase_data[$k]['num'] = (int)$v['num'];
                    $purchase_data[$k]['real_num'] = (int)$v['real_num'];
                }
            } else {
                $msg = '更新数据';
                //更新数据
                if (!empty($post['wl_num'])) {
                    $post['wl_num'] = implode(',', $post['wl_num']);
                } else {
                    $post['wl_num'] = '';
                }
                if (!empty($post['order_num'])) {
                    $post['order_num'] = implode(',', $post['order_num']);
                } else {
                    $post['order_num'] = '';
                }
                if (!empty($post['purchase_data'])) {
                    $draft = $is_draft == 0 ? 4 : 5;
                    foreach ($post['purchase_data'] as $k => $value) {
                        table('purchase')->where(['id' => $value['id']])->update(['real_num' => $value['real_num'], 'apply_status' => $draft]);
                    }
                }
                $data = [
                    'order_num' => $post['order_num'],
                    'purchase_price' => $post['purchase_price'],
                    'wl_num' => $post['wl_num'],
                    'real_num' => $post['real_num'],
                    'sum_num' => $post['sum_num'],
                ];
                table('dcg')->where(['union_batch' => $post['union_batch']])->update($data);
                // foreach ($purchase_data as $key => $value) {
                //     table('purchase')->where(['id' => $value['id']])->update(['real_num' => $value['real_num'], 'apply_status' => 4]);
                // }
            }
            $data2['purchase_data'] = $purchase_data;
            $data2['dcg_info'] = $dcg_info;
            $data2['id'] = $id;
            $data2['msg'] = $msg;
            return success('操作成功', $data2);
        } else {
            $data = [
                'code' => 1,
                'msg' => '显示数据',
                'data' => $dcg_info,
                'purchase_data' => $purchase_data,
                'id' => $id,
            ];
            return json($data);
        }
    }


    //审核采购申请
    // public function edit_purchase_apply()
    // {
    //     $post = $this->request->post();
    //     //获取审核列表id值
    //     $id = !empty($post['id']) ? $post['id'] : 1;
    //     $check_info = table('check')->where(['id' => $id])->find();
    //     $product_id = $check_info['product_id'];
    //     $batch = $check_info['batch'];
    //     $product_variants = table('productvariants')->where(['product_id' => $product_id])->select()->toarray();
    //     $color = array_values(array_unique(array_column($product_variants, 'option1')));
    //     $size = array_values(array_unique(array_column($product_variants, 'option2')));
    //     $cup = array_values(array_unique(array_column($product_variants, 'option3')));
    //     if (!empty($size) && !empty($cup)) {
    //         foreach ($size as  $v) {
    //             foreach ($cup as  $vl) {
    //                 $size_cup[] = $v . $vl;
    //             }
    //         }
    //     } else {
    //         $size_cup = $size;
    //     }
    //     array_unshift($size_cup, 'color');
    //     array_push($size_cup, 'color_sum');
    //     $table_header = $size_cup;
    //     if (count($post) == 1) {
    //         $output_detail  =  mgtable('purchase')->field($table_header)->where(['batch' => $batch])->select()->toarray();
    //         $data = [
    //             'code' => 1,
    //             'msg' => '',
    //             'table_header' => $table_header,
    //             'options' => get_options($color),
    //             'list' => $output_detail,
    //         ];
    //         return json($data);
    //     }
    //     $data = $post['sku'];
    //     //生成需要添加的格式
    //     foreach ($data as $k => $v) {
    //         foreach ($v as $kl => $vl) {
    //             foreach ($table_header as $kll => $vll) {
    //                 if ($kll == $kl) {
    //                     $new_data[$k][$vll] = $vl;
    //                 }
    //             }
    //         }
    //     }
    //     foreach ($new_data as $key => $value) {
    //         //更新详情值
    //         mgtable('purchase')->where(['batch' => $batch, 'color' => $value['color']])->update($value);
    //     }
    //     mgtable('purchase')->where(['batch' => $batch])->update(['status' => $post['status']]);
    //     $check_data['status'] = $post['status'];
    //     $check_data['content'] = $post['content'];
    //     $check_data['rep_num'] = $post['rep_num'];
    //     table('check')->where(['batch' => $post['batch']])->update($check_data);
    //     return success('审核成功');
    // }

    // public function edit_purchase_apply_back()
    // {
    //     $post = $this->request->post();
    //     //获取审核列表id值
    //     $id = !empty($post['id']) ? $post['id'] : 1;
    //     $check_info = table('check')->where(['id' => $id])->find();
    //     $output_id = $check_info['product_id'];
    //     $batch = $check_info['batch'];
    //     $table_header = table('output' . $output_id)->order(['id' => 'asc'])->find();
    //     unset($table_header['id'], $table_header['batch'], $table_header['status'], $table_header['admin_id'], $table_header['create_time'], $table_header['order_num']);
    //     $table_header = array_keys($table_header);
    //     if (count($post) == 1) {
    //         $output_detail  =  table('output' . $output_id)->where(['batch' => $batch])->select()->toarray();
    //         $str = 'idbatchstatusadmin_idcreate_timeorder_num';
    //         foreach ($output_detail as $k => $v) {
    //             foreach ($v as $kl => $vl) {
    //                 if (strpos($str, $kl) === false) {
    //                     $output_detail_n[$k][$kl] = $vl;
    //                 }
    //             }
    //         }
    //         foreach ($output_detail_n as $key => $value) {
    //             $output_detail_new[$key] = array_values($value);
    //         }
    //         $data = [
    //             'code' => 1,
    //             'msg' => '',
    //             'table_header' => $table_header,
    //             // 'options' => get_options($output_id),
    //             'list' => $output_detail_new,
    //         ];
    //         return json($data);
    //     }
    //     $data = $post['sku'];
    //     //生成需要添加的格式
    //     foreach ($data as $k => $v) {
    //         foreach ($v as $kl => $vl) {
    //             foreach ($table_header as $kll => $vll) {
    //                 if ($kll == $kl) {
    //                     $new_data[$k][$vll] = $vl;
    //                 }
    //             }
    //         }
    //     }
    //     foreach ($new_data as $key => $value) {
    //         //更新详情值
    //         table('output' . $output_id)->where(['batch' => $batch, 'color' => $value['color']])->update($value);
    //     }
    //     table('output' . $output_id)->where(['batch' => $batch])->update(['status' => $post['status']]);
    //     $check_data['status'] = $post['status'];
    //     $check_data['content'] = $post['content'];
    //     $check_data['rep_num'] = $post['rep_num'];
    //     table('check')->where(['batch' => $post['batch']])->update($check_data);
    //     return success('审核成功');
    // }


    public function export_detail()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $fields = $this->request->get('fields');
        $fields = json_decode($fields, true);

        $header = [];
        foreach ($fields as $vo) {
            $header[] = [$vo['comment'], $vo['field']];
        }
        $post = $this->request->post();
        $output_id = input('output_id');
        if (empty($output_id)) {
            //获取id值
            $output_id = !empty($post['output_id']) ? $post['output_id'] : 1;
        }
        //查询列表
        $table_header = table('output' . $output_id)->where(['id' => 1])->find();
        $table_header = get_table_header(array_keys($table_header));
        $list = table('output' . $output_id)->select()->toarray();
        $fileName = "export_output_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    // 编号采购成本列表
    public function add_purchaseprice()
    {
        //显示列表
        // 8059053670619
        $post = $this->request->post();
        if (empty($post['product_id'])) {
            return error('网络错误请稍后再试');
        }
        $product_id = $post['product_id'];
        $brand_cost = table('brandcost')->where(['product_id' => $product_id])->order(['month' => 'desc'])->select()->toarray();
        if (!empty($brand_cost)) {
            foreach ($brand_cost as $k => $v) {
                $brand_cost[$k]['month'] = date('Y-m-d', $v['month']);
            }
        }

        $product_variants = table('productvariants')->field('sku,price')->where(['product_id' => $product_id])->select()->toarray();
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $brand_cost,
            'sku_list' => $product_variants,
            'product_id' => $product_id,
        ];
        return json($data);
    }

    // 编号采购成本列表
    public function add_purchaseprice2()
    {
        //显示列表
        // 8059053670619
        $post = $this->request->post();
        if (empty($post['product_id'])) {
            return error('网络错误请稍后再试');
        }
        if (empty($post['month'])) {
            return error('请填写月份');
        }
        $product_variants = table('skucost')->where(['product_id' => $post['product_id'], 'month' => $post['month']])->select()->toarray();
        if (empty($product_variants)) {
            $product_variants = table('productvariants')->field('sku,price')->where(['product_id' => $post['product_id']])->select()->toarray();
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'sku_list' => $product_variants,
            'product_id' => $post['product_id'],
        ];
        return json($data);
    }
    /**
     * 方法详情
     * @param array params
     */
    public function add_purchaseprice3()
    {
        $post = $this->request->post();
        $sku_list = array();
        if (!empty($post['sku_list'])) {
            foreach ($post['sku_list'] as $k => $v) {
                $sku_list[$k]['price'] = $post['brand_cost'];
                $sku_list[$k]['sku'] = $v['sku'];
            }
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $sku_list,
        ];
        return json($data);
    }

    //添加操作

    public function edit_purchaseprice()
    {
        $post = $this->request->post();
        //通过对应的时间  商品id   和sku查询对应的数据  有则更新  没有则插入
        $brandcost =  table('brandcost')->where(['product_id' => $post['product_id'], 'month' => $post['month']])->find();
        if (!empty($brandcost)) {
            //更新对的数据
            table('brandcost')->where(['product_id' => $post['product_id'], 'month' => $post['month']])->update(['brand_cost' => $post['brand_cost']]);
        } else {
            //插入对应的数据
            table('brandcost')->insert(['product_id' => $post['product_id'], 'month' => $post['month'], 'brand_cost' => $post['brand_cost']]);
        }
        //循环sku
        $sku = $post['sku'];
        foreach ($sku as  $value) {
            $skucost =  table('skucost')->where(['product_id' => $post['product_id'], 'month' => $post['month'], 'sku' => $value['sku']])->find();
            if (!empty($skucost)) {
                //更新对应的值
                table('skucost')->where(['product_id' => $post['product_id'], 'month' => $post['month'], 'sku' => $value['sku']])->update(['price' => $value['price']]);
            } else {
                //直接插入
                table('skucost')->insert(['product_id' => $post['product_id'], 'month' => $post['month'], 'sku' => $value['sku'], 'price' => $value['price']]);
            }
        }
        return success('操作成功');
    }
}
